package org.pewpew.client;

import java.util.List;

import org.pewpew.model.Player;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

public class Hardware {
	
	private Player playerPhysicalState = new Player ();
	
	public void setUsername (String name) {
		playerPhysicalState.setUsername(name);
	}
	
	public Player getPlayer() {
		return playerPhysicalState.getCopy ();
	}
	
	public boolean isReady() {
		return playerPhysicalState.getUsername() != null && 
			Math.abs (playerPhysicalState.getLatitude() + playerPhysicalState.getLongitude()) > 1E-10;//coords were set
	}
	
	public void setUpOrientationListener(Context context) {
		SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
		List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
		if (sensors.size() == 0) {
			Log.e("PEWPEW", "No ORIENTATION Sensor");
			//Toast.makeText(context, "No ORIENTATION Sensor",Toast.LENGTH_LONG).show();
			//throw new IllegalStateException("Cannot run on a device that have no orientation sensor");
		} else {
			sensorManager.registerListener(new SensorEventListener() {
				public void onSensorChanged(SensorEvent event) {
					playerPhysicalState.setOrientation(event.values[0]);
				}
	
				public void onAccuracyChanged(Sensor sensor, int accuracy) {
				}
			}, sensors.get(0), SensorManager.SENSOR_DELAY_NORMAL);
		}
	}

	public void setUpGPSListener(Context context) {
		//TODO duplicate add listener
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		LocationListener locationListener = new LocationListener() {
			public void onLocationChanged(Location location) {
				playerPhysicalState.setLatitude(location.getLatitude());
				playerPhysicalState.setLongitude(location.getLongitude());
				Log.i("PEW-hardware", "location set: " + location.getLatitude() + " " + location.getLongitude());
			}
	
			public void onStatusChanged(String provider, int status, Bundle extras) {}
	
			public void onProviderEnabled(String provider) {}
	
			public void onProviderDisabled(String provider) {}
		};
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
	}

}
